;!function () {
  var addClass = ns.addClass
  var getWindowSize = ns.getWindowSize
  var getRelativePos = ns.getRelativePos
  var bindEasy = ns.bindEasy
  var throttle = ns.throttle
  var removeClass = ns.removeClass
  var defaultType = ns.defaultType
  var removeElement = ns.removeElement
  var getByClass = ns.getByClass
  var toNumber = ns.toNumber
  var getType = ns.getType

  var mouseWheel = ns.mouseWheel

  function emptyFunc () {}

  var static_index = 500
  var pop_id_prefix = 'pop-id-'
  var FUNCTION = 'Function'

  // 记录所有的弹窗实例化对象
  window['iPops'] = defaultType('Object', window['iPops'])
  iPops.num = defaultType('Number', iPops.num)

  // 生成弹窗实例化id
  function createPopID () {
    var cNum =  iPops.num + 1
    iPops.num = cNum
    return pop_id_prefix + cNum
  }

  function toFunc (data) {
    return defaultType(FUNCTION, data)
  }


  // 清空并返回pop对象长度
  function getAndClearPopObjLength (obj) {
    var num = 0
    for(var key in obj) {
      if(!obj[key]) {
        delete obj[key]
      }else {
        obj[key].getStatus() && num++
      }      
    }
    return num
  }



  // 禁止鼠标滚动
  function disabledScroll (el) {
    mouseWheel(el, false, true)
  }

  function ShowDom (opt) {
    var el = opt.el;    
    if(!el) return;
    var current_id = createPopID()
    var is_show = false;//是否已显示
    var autoClose = toNumber(opt.autoClose)
    var close_timer = null;
    var doingCloseing = false

    var t_time = defaultType('Number', opt.transitionTime, 200)
    
    addClass(el, 'show-dom')
    //disabledScroll(el)
    var oFather = opt.oFather || document.body;

    oFather.pop = defaultType('Object', oFather.pop)
    

    var space = opt.space; // 离父级的间距
    var x = 0; //弾层的x坐标
    var y = 0; //弾层的y坐标

    if(opt.mask && !oFather.oMask) {
      var maskClick = opt.maskClick===false ? false : true;
      var mk = document.createElement('div')
      mk.className = 'show-dom-mask'
      mk.style.zIndex = static_index + iPops.num - 1
      oFather.appendChild(mk)
      disabledScroll(mk)
      mk.onclick = function () {
        if(!maskClick) return;
        var maxid = -1
        for(var key in oFather.pop) {
          var id = toNumber(key.replace(pop_id_prefix, ''))
          maxid = maxid < id ? id : maxid          
        }
        confirmToClose()
      }
      oFather.oMask = mk
    }    
    
    function posNum (num, min) { return num <=min ? min : num; };    

    // 取父级容器的边界为最小值
    var THOT_POS = throttle(function () {
      if(!el || doingCloseing) return; 
      setPos(function (x, y) {
        Tween.move(el, {left: x, top: y}, 500, Tween.Cubic.easeOut)
      })
    }, 300, true, true)
  
    function show () {
      if(getType(opt.startShow)==FUNCTION) {
        opt.startShow(confirmShow)
      }else {
        confirmShow()
      }      
    }

    function close (step) {
      clearInterval(close_timer)
      // 关闭前确认
      if(getType(opt.startClose)==FUNCTION) {
        opt.startClose(step, function () {
          confirmToClose('close-check')
        })
      }else {
        confirmToClose(step)
      }      
    }

    // 确认显示
    function confirmShow () {
      is_show = true      
      setTimeout(function () {
        toFunc(opt.onPopNumChange)(oFather.pop, getAndClearPopObjLength(oFather.pop)); // 弹窗数量改变
        el.style.zIndex = static_index + iPops.num      
        el.style.display = 'inline-block';
        setPos(function (x, y) {
          el.style.left = x + 'px'
          el.style.top = y + 'px'
          setTimeout(function () {
            addClass(el, 'showed')
            
            oFather.oMask && Tween.move(oFather.oMask, {opacity: 1}, t_time, Tween.Linear)
            Tween.move(el, {opacity: 1}, t_time, Tween.Linear, function () {
              bindEasy(window, 'scroll', THOT_POS)
              bindEasy(window, 'resize', THOT_POS)
              removeClass(el, ['ready-show'])
              chekcAutoClose()
              toFunc(opt.onShowed)()
            })
          }, 17);
        });
      }, 17)      
    }

    function chekcAutoClose () {
      clearInterval(close_timer)
      if(!autoClose) return;
      autoClose = autoClose < 17 ? 17 : autoClose
      toFunc(opt.countDown)(autoClose)
      close_timer = setInterval(function () {
        autoClose -= 1000
        if(autoClose<0){
          autoClose = 0
        }
        toFunc(opt.countDown)(autoClose)
        !autoClose && close()
      }, 1000);
    }



    // 确定关闭
    function confirmToClose (step) {
      doingCloseing = true
      delete oFather.pop[current_id]
      var iPopNums = getAndClearPopObjLength(oFather.pop);
      addClass(el, 'before-close')
      setTimeout(function () {
        is_show = false;
        removeClass(el, 'showed')
        !iPopNums && Tween.move(oFather.oMask, {opacity: 0}, t_time, Tween.Linear, function () {
          removeElement(oFather.oMask)
          oFather.oMask = null
        })
        
        Tween.move(el, {opacity: 0}, t_time, Tween.Linear, function () {
          removeClass(el, ['ready-show', 'show-dom', 'before-close'])
          el.removeAttribute('style')
          opt.newWrapper && removeElement(el)
          
          toFunc(opt.onClosed)(step)
        })
      }, 17);
    }
    

    // 计算位置
    function setPos (callback) {      
      var r = getWindowSize(); // 窗口尺寸
      if(oFather.tagName=='BODY') {
        var f_w = r.width
        var f_h = r.height        
      }else {
        var f_w =oFather.offsetWidth
        var f_h = oFather.offsetHeight
        
      }
      el.style['max-width'] = f_w-space * 2 + 'px';
      el.style['max-height'] = f_h-space * 2 + 'px';
      setTimeout(function () {        
        var s = getRelativePos(el); // 弾层的尺寸及位置
        var t = oFather.tagName!='BODY' ? getRelativePos(oFather) : {x: 0, y: 0, width: r.width, height: r.height}; // 父级容器的尺寸及位置
        x = t.x + (t.width - s.width) / 2
        y = t.y + (t.height - s.height) / 2
        x = posNum(x, t.x)
        y = posNum(y, t.y)

        var mk = oFather.oMask;
        if(mk) {          
          if(oFather.tagName=='BODY') {
            mk.style['left'] = 0
            mk.style['top'] = 0
            mk.style['right'] = 0
            mk.style['bottom'] = 0            
          }else {
            mk.style['width'] = t.width + 'px'
            mk.style['height'] = t.height + 'px'
            mk.style['left'] = t.x + 'px'
            mk.style['top'] = t.y + 'px'
          }
        }

        addClass(el, 'ready-show')
        setTimeout(function () {
          callback(x, y)
        }, 17);
      }, 17);
    }

    show();

    
    var resDom = {
      show: show,
      close: close,
      is_show: is_show,
      getStatus: function () {
        return is_show
      }
    }
    iPops[current_id] = resDom
    oFather.pop[current_id] = resDom
    return resDom
  };

  function dialog (opt) {
    opt = defaultType('Object', opt)
    var all = []
    var el = document.createElement('div');
    var cancelText = opt.cancelText
    var autoClose = toNumber(opt.autoClose)
		var showTip = opt.showTip === true ? true : false
    autoClose = changeTime(autoClose)

    el.className = 'bt-dialog-wrapper';
    el.innerHTML = '\
      <div class="btdg-header">\
        <h4>'+ (opt.title || '提示') +'</h4>\
        <span class="clstime">'+ autoClose +'s</span>\
        <i class="btdg-close"></i>\
      </div>\
      <div class="btdg-content">'+ (opt.msg || '') +'</div>\
      <div class="btdg-btns">\
        '+ (!cancelText ? "" : '<span class="cancel bt-btn">'+ cancelText +'</span>') +'\
        <span class="confirm bt-btn bgcolor">'+ (opt.confirmText || '确定') +'</span>\
      </div>\
      <div class="btdg-tip">\
        <span>下面还有<b class="lasn"></b>个层</span>\
        <span class="coa">关闭全部</span>\
      </div>\
    ';
    try {
      opt.oFather.appendChild(el);
    }catch(e) {
      document.body.appendChild(el);
    }
    var oNumWrapper = getByClass('lasn', el)[0]
    getByClass('coa', el)[0].onclick = function () {
      for(var key in all) {
        all[key].close()
      }
    }

    var oTip = getByClass('btdg-tip', el)[0]
    var oTimeWrapper = getByClass('clstime', el)[0]


    function changeTime (time) {
      autoClose = Math.ceil(time/1000)
      if(oTimeWrapper) {
        oTimeWrapper.innerHTML = '(' + autoClose + 's)'
        oTimeWrapper.style.display = autoClose ? 'inline-block' : 'none'
      }
    }

    opt.el = el
    opt.newWrapper = true;//是否是创建的容器。关闭会自动删除
    opt.mask = opt.mask===false ? false : true;
    
    opt.onPopNumChange = function (allIpop, num) {
			if(!showTip) return;
      all = allIpop;
      oNumWrapper.innerHTML = num-1
      oTip && (oTip.style.display = num>1 ? 'block' : 'none');
    }    

    opt.countDown = function (time) {
      changeTime(time)
    }
    
    var pop = ShowDom(opt)


    var oCancel = getByClass('cancel', el)[0]
    getByClass('confirm', el)[0].onclick = function () {
      pop.close('confirm')
    }
    getByClass('btdg-close', el)[0].onclick = function () {
      pop.close('close')
    }
    oCancel && (oCancel.onclick = function () {
      pop.close('calcenl')
    });
  }



  // 创建加载动画
  function createLoading (iconHtml) {
    var el = document.createElement('div');
    el.className = 'BT-loading'

    iconHtml = iconHtml || '\
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="20px" height="20px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">\
      <path fill="#fff" d="M43.935,25.145c0-10.318-8.364-18.683-18.683-18.683c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615c8.072,0,14.615,6.543,14.615,14.615H43.935z">\
        <animateTransform attributeType="xml"\
          attributeName="transform"\
          type="rotate"\
          from="0 25 25"\
          to="360 25 25"\
          dur="0.6s"\
          repeatCount="indefinite"/>\
        </path>\
      </svg>\
    ';

    el.innerHTML = '\
      <div class="svg-box">\
        '+ iconHtml +'\
      </div>\
      <div class="ld-text"></div>\
    ';
    document.body.appendChild(el);

    var loading_close_timer = null

    var oText = getByClass('ld-text', el)[0]

    function show (msg) {
      clearTimeout(loading_close_timer)
      oText.innerHTML = msg || '加载中'
      el.style.display = 'flex'
      setTimeout(function () {
        addClass(el, 'active')
      }, 17)
    }

    function close () {
      removeClass(el, 'active')
      loading_close_timer = setTimeout(function () {
        el.style.display = 'none'
      }, 200)
    }

    return {
      show: show,
      close: close
    }
  }

  ns.ShowDom = ShowDom
  ns.dialog = dialog
  ns.createLoading = createLoading
} ();



